package serializer

import (
	"simple-mail/entity"

	"github.com/gin-gonic/gin"
)

const (
	codeOK        = 0
	codeParamErr  = 400
	codeServerErr = 500
)

// CommonPage 分页参数
type CommonPage struct {
	Page int `json:"page" binding:"required,min=1"`
	Size int `json:"size" binding:"required,min=1"`
}

// CommonResponse 通用返回
type CommonResponse struct {
	Success      bool        `json:"success"`
	Data         interface{} `json:"data"`
	ErrorCode    int         `json:"errorCode"`
	ErrorMessage string      `json:"errorMessage"`
}

// ResponseOkWithData 带data的成功返回
func ResponseOkWithData(c *gin.Context, data interface{}) {
	c.JSON(200, CommonResponse{
		Success:      true,
		Data:         data,
		ErrorCode:    codeOK,
		ErrorMessage: "",
	})
}

// ResponseOkWithDataPage 带分页data的成功返回
func ResponseOkWithDataPage(c *gin.Context, data interface{}, p entity.PageEntity) {
	c.JSON(200, CommonResponse{
		Success:      true,
		ErrorCode:    codeOK,
		ErrorMessage: "",
		Data: map[string]interface{}{
			"list": data,
			"pagination": map[string]int{
				"currentPage":  p.CurrentPage,
				"pageSize":     p.PageSize,
				"pagesCount":   p.PagesCount,
				"recordsCount": p.RecordsCount,
			},
		},
	})
}

// ResponseOkWithDataPageExtra 带分页data与扩展数据的成功返回
func ResponseOkWithDataPageExtra(c *gin.Context, data interface{}, p entity.PageEntity, extra map[string]interface{}) {
	dataMap := map[string]interface{}{
		"list": data,
		"pagination": map[string]int{
			"currentPage":  p.CurrentPage,
			"pageSize":     p.PageSize,
			"pagesCount":   p.PagesCount,
			"recordsCount": p.RecordsCount,
		},
	}
	for key, val := range extra {
		dataMap[key] = val
	}
	c.JSON(200, CommonResponse{
		Success:      true,
		ErrorCode:    codeOK,
		ErrorMessage: "",
		Data:         dataMap,
	})
}

// ResponseOk 正常返回
func ResponseOk(c *gin.Context) {
	c.JSON(200, CommonResponse{
		Success:      true,
		ErrorCode:    codeOK,
		ErrorMessage: "",
	})
}

// ResponseParamErrWithMsg 参数错误,带msg
func ResponseParamErrWithMsg(c *gin.Context, msg string) {
	c.JSON(200, CommonResponse{
		Success:      false,
		ErrorCode:    codeParamErr,
		ErrorMessage: msg,
	})
}

// ResponseParamErr 参数错误
func ResponseParamErr(c *gin.Context) {
	c.JSON(200, CommonResponse{
		Success:      false,
		ErrorCode:    codeParamErr,
		ErrorMessage: "参数错误",
	})
}

// ResponseServerErr 服务器异常
func ResponseServerErr(c *gin.Context, msg string) {
	c.JSON(200, CommonResponse{
		Success:      false,
		ErrorCode:    codeServerErr,
		ErrorMessage: msg,
	})
}
